package com.muyu.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.muyu.common.core.domain.Result;
import com.muyu.common.core.utils.DateUtils;
import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser;
import com.muyu.system.Bo.DmShoppingGoodsBo;
import com.muyu.system.Vo.DmShoppingGoodsVo;
import com.muyu.system.Vo.InventorySkuVO;
import com.muyu.system.Vo.InventoryVO;
import com.muyu.system.domain.*;
import com.muyu.system.dto.InventoryDTO;
import com.muyu.system.dto.OrderGoods;
import com.muyu.system.dto.UpdateInventoryDTO;
import com.muyu.system.mapper.*;
import com.muyu.system.service.IDmShoppingGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-16
 */
@Service
public class DmShoppingGoodsServiceImpl implements IDmShoppingGoodsService {
    @Autowired
    private DmShoppingGoodsMapper dmShoppingGoodsMapper;
    @Autowired
    private DmShoppingSkuMapper dmShoppingSkuMapper;
    @Autowired
    private DmShoppingStoreMapper dmShoppingStoreMapper;

    @Autowired
    private DanmoProductFootprintMapper danmoProductFootprintMapper;
    @Autowired
    private DanmoShoppingProductsCollectionMapper danmoShoppingProductsCollectionMapper;

    @Autowired
    private SecurityDepositAccountMapper securityDepositAccountMapper;
    /**
     * 查询商品
     *
     * @param id 商品主键
     * @return 商品
     */
    @Override
    public DmShoppingGoodsVo selectDmShoppingGoodsById(Long id) {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        // 查询商品足迹
        List<DanmoProductFootprint> danmoProductFootprintList = danmoProductFootprintMapper.selectProuct(loginUser.getUserid(), id);
        boolean hasTodayRecord = false;
        // 先判断一下商品中是否有该商品的今天的足迹
        if (!danmoProductFootprintList.isEmpty()) {
            for (DanmoProductFootprint danmoProductFootprint : danmoProductFootprintList) {
                if (isToday(danmoProductFootprint.getBrowseTime())) {
                    // 将更新时间修改为当前时间
                    danmoProductFootprint.setUpdateTime(DateUtils.getNowDate());
                    danmoProductFootprintMapper.updateDanmoProductFootprint(danmoProductFootprint);
                    hasTodayRecord = true;
                    break;
                }
            }
        }
        if (!hasTodayRecord) {
            DanmoProductFootprint build = DanmoProductFootprint.builder()
                    .userId(loginUser.getUserid())
                    .productId(id)
                    .browseTime(DateUtils.getNowDate())
                    .types(1L)
                    .createTime(DateUtils.getNowDate())
                    .build();

            danmoProductFootprintMapper.insertDanmoProductFootprint(build);
        }
        DmShoppingSku dmShoppingSku = new DmShoppingSku();
        dmShoppingSku.setGoodsId(id);
        DmShoppingGoods dmShoppingGoods = dmShoppingGoodsMapper.selectDmShoppingGoodsById(id);
        DmShoppingStore dmShoppingStore = dmShoppingStoreMapper.selectDmShoppingStoreById(dmShoppingGoods.getStoreId());
        DmShoppingGoodsVo dmShoppingGoodsVo = BeanUtil.toBean(dmShoppingGoods, DmShoppingGoodsVo.class);
        List<DmShoppingSku> dmShoppingSkuList = dmShoppingSkuMapper.selectDmShoppingSkuList(dmShoppingSku);
        dmShoppingGoodsVo.setDmShoppingSkuList(dmShoppingSkuList);
        dmShoppingGoodsVo.setDmShoppingStore(dmShoppingStore);
        DanmoShoppingProductsCollection danmoShoppingProductsCollection = new DanmoShoppingProductsCollection();
        danmoShoppingProductsCollection.setUserId(loginUser.getUserid());
        danmoShoppingProductsCollection.setGoodsId(id);
        DanmoShoppingProductsCollection danmoShoppingProductsCollection1 = danmoShoppingProductsCollectionMapper.selectDanmoShoppingProductsCollectionLists(danmoShoppingProductsCollection);
        if (danmoShoppingProductsCollection1 != null){
            dmShoppingGoodsVo.setWhetherToCollect(true);
        }
        if (danmoShoppingProductsCollection1 == null){
            dmShoppingGoodsVo.setWhetherToCollect(false);
        }

        return dmShoppingGoodsVo;
    }

    private boolean isToday(Date date) {
        Date now = DateUtils.getNowDate();
        java.util.Calendar cal1 = java.util.Calendar.getInstance();
        java.util.Calendar cal2 = java.util.Calendar.getInstance();
        cal1.setTime(date);
        cal2.setTime(now);
        return cal1.get(java.util.Calendar.YEAR) == cal2.get(java.util.Calendar.YEAR)
                && cal1.get(java.util.Calendar.DAY_OF_YEAR) == cal2.get(java.util.Calendar.DAY_OF_YEAR);
    }

    /**
     * 查询商品列表
     *
     * @param dmShoppingGoods 商品
     * @return 商品
     */
    @Override
    public IPage<DmShoppingGoodsVo> selectDmShoppingGoodsList(DmShoppingGoods dmShoppingGoods) {
        IPage<DmShoppingGoods> dmShoppingGoodsList = dmShoppingGoodsMapper.selectDmShoppingGoodsList(new Page<>(dmShoppingGoods.getPageNum(),dmShoppingGoods.getPageSize()),dmShoppingGoods);
         DmShoppingSku dmShoppingSku = new DmShoppingSku();
        if(dmShoppingGoods.getId() != null ){
            dmShoppingSku.setGoodsId(dmShoppingGoods.getId());
        }
        List<DmShoppingSku> dmShoppingSkuList = dmShoppingSkuMapper.selectDmShoppingSkuList(dmShoppingSku);
        Map<Long,Long> inventoryMap = dmShoppingSkuList.stream().collect(Collectors.toMap(DmShoppingSku::getGoodsId, DmShoppingSku::getNum,Long::sum));
        List<Long> list = dmShoppingGoodsList.getRecords().stream().map(DmShoppingGoods::getId).toList();
        Map<Long, List<OrderGoods>> collect = new HashMap<>();
        if(!list.isEmpty()){
            List<OrderGoods> orderByGoodsId = dmShoppingSkuMapper.findOrderByGoodsId(list);
            collect = orderByGoodsId.stream().collect(Collectors.groupingBy(OrderGoods::getGoodsId));
        }
        Map<Long, List<OrderGoods>> finalCollect = collect;
        DateTime dateTime = DateUtil.offsetMonth(DateUtil.date(), -1);
        IPage<DmShoppingGoodsVo> convert = dmShoppingGoodsList.convert(item -> {
            DmShoppingGoodsVo vo = BeanUtil.copyProperties(item, DmShoppingGoodsVo.class);
            Long inventory = inventoryMap.get(item.getId());
            vo.setInventory(inventory);
            vo.setCount(0);
            vo.setMoonCount(0);
            if(!finalCollect.isEmpty()){
                List<OrderGoods> orderGoods = finalCollect.get(item.getId());
                vo.setCount(0);
                vo.setMoonCount(0);
                if(null != orderGoods){
                    vo.setCount(orderGoods.stream().mapToInt(OrderGoods::getQuantity).sum());
                    int sum = orderGoods.stream().filter(a -> DateUtil.isIn(DateUtil.date(a.getCreateTime()), dateTime, DateUtil.date()))
                            .mapToInt(OrderGoods::getQuantity).sum();
                    vo.setMoonCount(sum);
                }
            }
            return vo;
        });
        return convert;
    }

    /**
     * 新增商品
     *
     * @param dmShoppingGoodsBo 商品
     * @return 结果
     */
    @Transactional
    @Override
    public int insertDmShoppingGoods(DmShoppingGoodsBo dmShoppingGoodsBo) {
        // 判断当前商户是否已经缴纳保证金
        SecurityDepositAccount one = new LambdaQueryChainWrapper<>(securityDepositAccountMapper).eq(SecurityDepositAccount::getStoreId, dmShoppingGoodsBo.getStoreId())
                .one();
        if(one == null){
            throw new RuntimeException("缺少保证金账户！");
        }
        if(one.getAmount() < one.getSecurityDeposit()){
            throw new RuntimeException("保证金不足！");
        }
        DmShoppingGoods dmShoppingGoods = BeanUtil.copyProperties(dmShoppingGoodsBo, DmShoppingGoods.class);
        dmShoppingGoods.setCreateTime(DateUtils.getNowDate());
        int flag = dmShoppingGoodsMapper.insertDmShoppingGoods(dmShoppingGoods);
        Long goodsId = dmShoppingGoods.getId();
        if (goodsId > 0 && dmShoppingGoodsBo.getDmShoppingSkuList() != null) {
            List<DmShoppingSku> dmShoppingSkuList = dmShoppingGoodsBo.getDmShoppingSkuList();
            Long finalGoodsId = goodsId;
            dmShoppingSkuList.stream().forEach(item -> {
                item.setGoodsId(Long.valueOf(finalGoodsId));
            });
            handleGoodsSku(dmShoppingSkuList);
        }
        return flag;
    }


    /**
     * 修改商品
     *
     * @param dmShoppingGoodsBo 商品
     * @return 结果
     */
    @Override
    public int updateDmShoppingGoods(DmShoppingGoodsBo dmShoppingGoodsBo) {
        dmShoppingGoodsBo.setUpdateTime(DateUtils.getNowDate());
        DmShoppingGoods dmShoppingGoods = BeanUtil.copyProperties(dmShoppingGoodsBo, DmShoppingGoods.class);
        int flag = 0;
        flag = dmShoppingGoodsMapper.updateDmShoppingGoods(dmShoppingGoods);
        if (dmShoppingGoodsBo.getDmShoppingSkuList() != null) {
            List<DmShoppingSku> dmShoppingSkuList = dmShoppingGoodsBo.getDmShoppingSkuList();
            for(DmShoppingSku dmShoppingSku : dmShoppingSkuList){
                dmShoppingSkuMapper.updateDmShoppingSku(dmShoppingSku);
                if(dmShoppingSku.getId() == null){
                    dmShoppingSkuMapper.insertDmShoppingSku(dmShoppingSku);
                }

            }
        }
        return flag;
    }

    /**
     * 批量删除商品
     *
     * @param ids 需要删除的商品主键
     * @return 结果
     */
    @Override
    public Result<Integer> deleteDmShoppingGoodsByIds(Long[] ids) {
        int i = dmShoppingGoodsMapper.deleteDmShoppingGoodsByIds(ids);
        return Result.success(i, "删除成功");
    }

    /**
     * 删除商品信息
     *
     * @param id 商品主键
     * @return 结果
     */
    @Override
    public Result<Integer> deleteDmShoppingGoodsById(Long id) {
        int i = dmShoppingGoodsMapper.deleteDmShoppingGoodsById(id);
        return  Result.success(i, "删除成功");
    }

    @Override
    public List<DmShoppingGoods> selectPriceSort(DmShoppingGoods dmShoppingGoods) {
        return null;
    }

    @Override
    public IPage<InventoryVO> inventory(InventoryDTO inventoryDTO) {
        Page<DmShoppingGoods> page = new LambdaQueryChainWrapper<>(dmShoppingGoodsMapper).eq(DmShoppingGoods::getStoreId, inventoryDTO.getStoreId())
                .select(DmShoppingGoods::getId, DmShoppingGoods::getGoodsName, DmShoppingGoods::getGoodsTitle)
                .page(new Page<>(inventoryDTO.getPageNum(), inventoryDTO.getPageSize()));
        IPage<InventoryVO> convert = page.convert(item -> {
            InventoryVO inventoryVO = new InventoryVO();
            BeanUtil.copyProperties(item, inventoryVO);
            List<DmShoppingSku> list = new LambdaQueryChainWrapper<>(dmShoppingSkuMapper).eq(DmShoppingSku::getGoodsId, item.getId()).list();
            List<InventorySkuVO> skuVOList = list.stream().map(a -> {
                InventorySkuVO inventorySkuVO = new InventorySkuVO();
                BeanUtil.copyProperties(a, inventorySkuVO);
                return inventorySkuVO;
            }).toList();
            inventoryVO.setSkuList(skuVOList);
            return inventoryVO;
        });
        return convert;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateInventory(List<UpdateInventoryDTO> list) {
        for (UpdateInventoryDTO updateInventoryDTO : list) {
            new LambdaUpdateChainWrapper<>(dmShoppingSkuMapper).eq(DmShoppingSku::getId, updateInventoryDTO.getSkuId())
                    .set(DmShoppingSku::getNum, updateInventoryDTO.getNum()).update();
        }

    }



    /**
     * 商品上传处理商品sku信息
     */
    public int handleGoodsSku(List<DmShoppingSku> dmShoppingSkuList) {
        int flag = 0;
        for (DmShoppingSku dmShoppingSku : dmShoppingSkuList) {
            flag = dmShoppingSkuMapper.insertDmShoppingSku(dmShoppingSku);
        }
        return flag;
    }
}
